package com.zhentao.studyim.controller;

import com.zhentao.studyim.dto.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

/**
 * 健康检查控制器
 * 用于检查系统各组件的运行状态
 */
@RestController
@RequestMapping("/api/health")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class HealthController {

    private final DataSource dataSource;
    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * 系统健康检查
     * GET /api/health
     */
    @GetMapping
    public ApiResponse<Map<String, Object>> health() {
        Map<String, Object> status = new HashMap<>();

        // 检查数据库连接
        try (Connection connection = dataSource.getConnection()) {
            status.put("database", "UP");
        } catch (Exception e) {
            status.put("database", "DOWN - " + e.getMessage());
        }

        // 检查Redis连接
        try {
            redisTemplate.opsForValue().set("health:check", "ok");
            String result = (String) redisTemplate.opsForValue().get("health:check");
            status.put("redis", "ok".equals(result) ? "UP" : "DOWN");
        } catch (Exception e) {
            status.put("redis", "DOWN - Redis服务未启动或连接失败");
        }

        status.put("application", "UP");
        status.put("timestamp", System.currentTimeMillis());

        return ApiResponse.success(status);
    }
}